
var list0 = require('../../data/cet4.js')
var list1 = require('../../data/cet6.js')
var list2 = require('../../data/primary.js')
var list3 = require('../../data/high.js')
var list4 = require('../../data/kaoyan.js')
var list5 = require('../../data/kaoyan_import.js')

var util = require('../../utils/util.js')
const db = wx.cloud.database()
const battleroom = db.collection('room')
//获取应用实例
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    player2img: '../../images/add-player.png',
    p2avatarUrl:'',//对手头像
    count: 0,       // onReady计数
    avatarUrl: '',  //本人头像
    room: '',       //房间号
    _id: '',      //数据标识
    show_select:true,//选择词库按钮
    start: false,   //玩家2进入后，控制玩家1界面的开始按钮显示
    p2: false,      //玩家2是否进入
    game: false,  //游戏是否开始
    started:false, //对手是否答题结束
    players: 0,
    bounceInDown: "animated bounceInDown ",


    da1: "",
    da2: "",
    da3: "",
    da4: "",
    showDaan: false,
    complete: false,
    true_num: 0,//本次正确数
    list: list0,//词库选择
    listnum: 2800,//随机数范围
    show: false,//控制下拉列表的显示隐藏，false隐藏、true显示
    selectData: ['四级', '六级', '初级词汇', '高中词汇', '考研', '专八'],//下拉列表的数据
    index: 0,//选择的下拉列表下标
    animationType: "animated bounce infinite", //初始的动画效果,

    color4:'black',
    color3: 'black',
    color2: 'black',
    color1: 'black',
    now_num:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (t) {
    var max_num = wx.getStorageSync("max_num")
    this.setData({
      max_num: max_num
    })

    var room = util.Room(new Date()) //获取房间号
    this.setData({
      room: room
    })
    let that = this
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: res => {
              console.log(res)
              that.setData({
                userInfo: res.userInfo,
                avatarUrl: res.userInfo.avatarUrl,
                nickName: res.userInfo.nickName
              })

              //判断是否是通过分享进入
              if (t.room) {
                this.setData({ show_select:false})
                console.log(t.room)
                var room = ''
                var p2=false
                var avatarUrl = []
                var data = t.room
                for (var i = 0; i < data.length; i++) {
                  if (data[i] === ',') {
                    that.setData({
                      i: ++i,
                      room: room
                    })
                    break;
                  }
                  room += (data[i])
                }
                for (var i = that.data.i; i < data.length; i++) {
                  avatarUrl += (data[i])
                  if (i === data.length - 1) {
                    if (avatarUrl == this.data.avatarUrl) {
                    this.setData({show_select:true}); break; } 
                    p2=true
                    that.setData({
                      p2avatarUrl: avatarUrl,
                      p2: true
                    })
                  }
                }
                if (p2 != true) { return; } 
                battleroom.add({  //通过分享进入后，往数据库添加一条数据
                  data: {
                    room: that.data.room,
                    nickName: res.userInfo.nickName,
                    avatarUrl: res.userInfo.avatarUrl,
                    player: 2,
                    started: 'no',
                    true_num:0
                  }, success: res => {
                    // 在返回结果中会包含新创建的记录的 _id
                    this.setData({
                      _id: res._id,
                    })
                  },
                })
              }
              that.onReady()
            }
          })
        }
      }
    })
    wx.showShareMenu({
      withShareTicket: true //显示当前页面的分享按钮
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    //this.getmessage()
    console.log("onReady")
    var count = this.data.count + 1
    this.setData({
      count: count
    })
    if (count > 1) {
      console.log("这是房间号：" + this.data.room)
      battleroom.where({
        room: this.data.room
      }).watch({              //本页核心:数据实时推送
        onChange: this.onChange.bind(this),
        onError(err) {
          console.error(err)
        }
      })
    }
  },

  onChange(snapshot) {
    console.log(snapshot)
    // 监听开始时的初始化数据
    if (snapshot.type === 'init') {
      //这里判断房间开始没开始（还没写）
    } else {
      for (const docChange of snapshot.docChanges) {
        // queueType:列表更新类型，表示更新事件对监听列表的影响
        switch (docChange.queueType) {
          // init	初始化列表
          // update	列表中的记录内容有更新，但列表包含的记录不变
          // enqueue	记录进入列表
          // dequeue	记录离开列表
          case 'enqueue': // 记录进入列表                         //玩家1 检测通过链接分享进入房间的人
            if (docChange.doc.avatarUrl !== this.data.avatarUrl && this.data.avatarUrl !== '' && docChange.doc.player == 2&&this.data.players==0) {
              console.log("有人进入，不是我自己")
              this.setData({
                p2avatarUrl: docChange.doc.avatarUrl,
                p2: true,
                start: true,
                players:1,
                show_select:false
              })
              var room = this.data.room
              battleroom.add({
                data: {
                  room: this.data.room,
                  nickName: this.data.nickName,
                  avatarUrl: this.data.avatarUrl,
                  player: 1,
                  started: 'no',
                  true_num: 0
                }, success: res => {
                  // 在返回结果中会包含新创建的记录的 _id
                  this.setData({
                    _id: res._id,
                  })
                },
              })
            }
            break
        }
        switch (docChange.queueType) {       //玩家2监听数据库的room状态，判断player1是否点击开始按钮
          case 'update': //	列表中的记录内容有更新，但列表包含的记录不变
            if (docChange.doc.avatarUrl !== this.data.avatarUrl && docChange.doc.player == 1 && docChange.doc.started === 'on') {
              this.setData({
                game: true,
                list: docChange.doc.checked
              })
              this.search()
            }
            if(docChange.doc.avatarUrl !== this.data.avatarUrl&& docChange.doc.started === 'end'){//监听对手答题结束 
            this.setData({
              started:true,
              true_num2: docChange.doc.true_num,
              geme: false,
            })
           // }
            }
        }
      }
    }
  },

  //玩家1点击开始，更新数据库的room状态
  start() {
    battleroom.doc(this.data._id).update({
      data: {
        started: 'on',
        checked: this.data.list
      }
    })
    this.setData({
      game: true
    })
    this.search()
  },

  //选择definition
  choice(e) {
    this.data.now_num++
     var checked=e.currentTarget.dataset['index']
    if (e.currentTarget.id === this.data.true_definition) {
      var true_btn =this.data.true_btn
     switch(true_btn){
       case 'color1': this.setData({ color1:"green" });break;
       case 'color2': this.setData({ color2: "green" }); break;
       case 'color3': this.setData({ color3: "green" }); break;
       case 'color4': this.setData({ color4: "green" }); break;
     }
      this.setData({ true_num: this.data.true_num + 1})
      console.log(this.data.color1 + this.data.color2 + this.data.color3 + this.data.color4)
      if (this.data.now_num < 5){
      this.next()
      }else{
        battleroom.doc(this.data._id).update({//答题结束后上传状态和得分
          data: {
            started: 'end',
            true_num:this.data.true_num
          }
        })
        console.log('头像二：'+this.data.p2avatarUrl)
        // if(this.data.started==true){
        this.setData({
          showDaan: true,
          now_num:0,
          geme: false,
        })
       // }
      }
    } else {
      switch(checked){
        case '1': this.setData({ color1: "red" }); break;
        case '2': this.setData({ color2: "red" }); break;
        case '3': this.setData({ color3: "red" }); break;
        case '4': this.setData({ color4: "red" }); break;
      }
      switch (true_btn) {
        case 'color1': this.setData({ color1: "green" }); break;
        case 'color2': this.setData({ color2: "green" }); break;
        case 'color3': this.setData({ color3: "green" }); break;
        case 'color4': this.setData({ color4: "green" }); break;
      }

      if (this.data.now_num < 5) {
       this.next()
      } else {
        battleroom.doc(this.data._id).update({//答题结束后上传状态
          data: {
            started: 'end',
            true_num: this.data.true_num
          }
        })
        console.log('头像二：' + this.data.p2avatarUrl)
        setTimeout(()=>{
          this.setData({
            showDaan: true,
            geme:false,
            now_num: 0
          })
        },400)
      
      }
    }
  },
  search() {
    var listnum = this.data.listnum
    console.log(listnum)
    var idx = Math.floor(Math.random() * listnum) + 1
    var list = this.data.list
    var word = list.wordList[idx]
    console.log(word)
    var that = this
    wx.request({
      url: 'https://api.shanbay.com/bdc/search/?word=' + word,
      data: {},
      method: 'GET',
      success: function (res) {
        setTimeout(() => {
          const innerAudioContext = wx.createInnerAudioContext()
          innerAudioContext.autoplay = true
          innerAudioContext.src = res.data.data.audio
          innerAudioContext.play()
          innerAudioContext.onPlay(() => {
          })
          that.setData({
            color4: 'black',
            color3: 'black',
            color2: 'black',
            color1: 'black',
            title: res.data.data.content,
            true_definition: res.data.data.definition
          })
        }, 400)
        var num = Math.floor(Math.random() * 400) + 1
        if (num < 100) {
          var da2 = list.wordList[Math.floor(Math.random() * listnum) + 1]
          that.search2(da2)
          var da3 = list.wordList[Math.floor(Math.random() * listnum) + 1]
          that.search3(da3)
          var da4 = list.wordList[Math.floor(Math.random() * listnum) + 1]
          that.search4(da4)
          setTimeout(() => {
            that.setData({
              da1: res.data.data.definition,
              da2: that.data.da22,
              da3: that.data.da33,
              da4: that.data.da44,
              true_btn: "color1"
            })
          }, 400)
        }
        if (100 < num && num < 200) {
          var da1 = list.wordList[Math.floor(Math.random() * listnum) + 1]
          that.search1(da1)
          var da3 = list.wordList[Math.floor(Math.random() * listnum) + 1]
          that.search3(da3)
          var da4 = list.wordList[Math.floor(Math.random() * listnum) + 1]
          that.search4(da4)
          setTimeout(() => {
            that.setData({
              da2: res.data.data.definition,
              da1: that.data.da11,
              da3: that.data.da33,
              da4: that.data.da44,
              true_btn: "color2"
            })
          }, 400)
        }
        if (num < 300 && num > 200) {
          var da2 = list.wordList[Math.floor(Math.random() * listnum) + 1]
          that.search2(da2)
          var da1 = list.wordList[Math.floor(Math.random() * listnum) + 1]
          that.search1(da1)
          var da4 = list.wordList[Math.floor(Math.random() * listnum) + 1]
          that.search4(da4)
          setTimeout(() => {
            that.setData({
              da3: res.data.data.definition,
              da2: that.data.da22,
              da1: that.data.da11,
              da4: that.data.da44,
              true_btn: "color3"
            })
          }, 400)
        }
        if (num > 300) {
          var da2 = list.wordList[Math.floor(Math.random() * listnum) + 1]
          var da22 = that.search2(da2)
          var da3 = list.wordList[Math.floor(Math.random() * listnum) + 1]
          that.search3(da3)
          var da1 = list.wordList[Math.floor(Math.random() * listnum) + 1]
          that.search1(da1)
          setTimeout(() => {
            that.setData({
              da4: res.data.data.definition,
              da2: that.data.da22,
              da1: that.data.da11,
              da3: that.data.da33,
              true_btn: "color4"
            })
          }, 400)
        }
      }
    })
  },
  search1(word) {
    var that = this
    wx.request({
      url: 'https://api.shanbay.com/bdc/search/?word=' + word,
      data: {},
      method: 'GET',
      success: function (res) {
        that.setData({
          da11: res.data.data.definition
        })
      }
    })
  },
  search2(word) {
    var that = this
    wx.request({
      url: 'https://api.shanbay.com/bdc/search/?word=' + word,
      data: {},
      method: 'GET',
      success: function (res) {
        that.setData({
          da22: res.data.data.definition
        })
      }
    })
  },
  search3(word) {
    var that = this
    wx.request({
      url: 'https://api.shanbay.com/bdc/search/?word=' + word,
      data: {},
      method: 'GET',
      success: function (res) {
        that.setData({
          da33: res.data.data.definition
        })
      }
    })
  },
  search4(word) {
    var that = this
    wx.request({
      url: 'https://api.shanbay.com/bdc/search/?word=' + word,
      data: {},
      method: 'GET',
      success: function (res) {
        that.setData({
          da44: res.data.data.definition
        })
      }
    })
  },
  next() {
    this.setData({ showDaan: false })

    this.search()
  },
  end() {
 
    wx.switchTab({
      url: '../test/test',
    })
  },

  again() {
    this.setData({
      showDaan: false,
      complete: false,
      num: 1,
      true_num: 0,
      animationType: "animated bounce infinite" //初始的动画效果
    })
    this.search()
  },



  // 点击下拉显示框
  selectTap() {
    this.setData({
      show: !this.data.show
    });
  },
  page_selectTap() {
    this.setData({
      show: false
    });
  },
  // 点击下拉列表
  optionTap(e) {
    let Index = e.currentTarget.dataset.index;//获取点击的下拉列表的下标
    switch (Index) {
      case 0: this.setData({ list: list0, listnum: 2894 }); break;
      case 1: this.setData({ list: list1, listnum: 2084 }); break;
      case 2: this.setData({ list: list2, listnum: 1526 }); break;
      case 3: this.setData({ list: list3, listnum: 3656 }); break;
      case 4: this.setData({ list: list4, listnum: 3837 }); break;
      case 5: this.setData({ list: list5, listnum: 817 }); break;
    }
    this.setData({
      index: Index,
      show: !this.data.show
    });
    console.log(this.data.selectData[Index])
  },

  /**
 * 生命周期函数--监听页面显示
 */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({
      start: false,
      complete: false,
      showDaan: false,
      show: false
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.setData({
      start: false,
      complete: false,
      showDaan: false
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (options) {
    var data = new Array(this.data.room, this.data.avatarUrl)
    console.log("分享" + data[0])
    return {          //分享传参：传递room号和player1的头像
      title: `${app.globalData.userInfo.nickName}邀请你加入英语单词大战游戏`,
      path: '/pages/online/online?room=' + data,
      imageUrl: '../../images/battle.jpg'
    }
  },

})

